package com.reggie.exception;

import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.PublicEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 早睡蛋
 * @Date 2022/7/25 11:54:41
 * @Desc: 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求参数异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultResponseVo handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return PublicEnums.FAIL.getResultResponseVo().setMessage(message);
    }

//    @ExceptionHandler(RuntimeException.class)
//    public ResultResponseVo exception(RuntimeException e) {
//        return PublicEnums.FAIL.getResultResponseVo().setMessage(e.getMessage());
//    }

}
